package com.bdqn.boot.yuanshen.service.impl;

import com.bdqn.boot.yuanshen.bean.Videos;
import com.bdqn.boot.yuanshen.mapper.VideosMapper;
import com.bdqn.boot.yuanshen.service.MinioService;
import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author Hasee
 * @version 1.0
 * @className MinioServiceimpl
 * @description TODD
 * @date 2025/3/5 11:06
 */
@Service
public class MinioServiceimpl implements MinioService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private VideosMapper videosMapper;
    @Override
    public String uploadFile(String bucket, String fileName, InputStream inputStream, String contentType) {
        try {
            // 确保桶存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            }

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucket)
                            .object(fileName)
                            .stream(inputStream, -1, 10485760) // 限制 10MB 分片
                            .contentType(contentType)
                            .build()
            );

            return  bucket + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getFileUrl(String bucket, String fileName) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucket)
                            .object(fileName)
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteFile(String bucket, String fileName) {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder().bucket(bucket).object(fileName).build()
            );
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void saveVideoInfoToDatabase(String fileName, String title, String description, String videoUrl, String coverUrl) {
        Videos video = new Videos();
        video.setUserId(1);
        video.setTitle(title);
        video.setDescription(description);
        video.setVideo_url(videoUrl);
        video.setCover_url(coverUrl);
        videosMapper.addVideos(video);
    }

    @Override
    public String uploadVideo(String bucket, MultipartFile file, String title, String description, String coverUrl) {
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();  // 获取文件名

            // 调用 uploadFile 方法上传文件到 MinIO
            String videoUrl = uploadFile(bucket, fileName, inputStream, file.getContentType());

            if (videoUrl != null) {
                // 保存视频信息到数据库
                saveVideoInfoToDatabase(fileName, title, description, videoUrl, coverUrl);
                return videoUrl;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    // 删除视频
    public boolean deleteVideo(String bucket, String fileName, int videoId) {
        try {
            // 1. 删除 MinIO 中的视频文件
            boolean deleteFile = deleteFileFromMinio(bucket, fileName);
            if (!deleteFile) {
                return false;  // 如果 MinIO 中的文件删除失败，则返回 false
            }

            // 2. 删除数据库中的视频记录
            videosMapper.deleteVideos(videoId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public boolean deleteFileFromMinio(String bucket, String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(fileName).build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateVideo(Videos video, MultipartFile newFile) {
        try {
            if (newFile != null && !newFile.isEmpty()) {
                // 先删除旧视频
                String oldVideoUrl = video.getVideo_url();
                String bucket = "videos";
                String oldFileName = oldVideoUrl.substring(oldVideoUrl.lastIndexOf("/") + 1);
                deleteFile(bucket, oldFileName);

                // 重新上传新视频
                String newFileName = System.currentTimeMillis() + "_" + newFile.getOriginalFilename();
                InputStream inputStream = newFile.getInputStream();
                String newVideoUrl = uploadFile(bucket, newFileName, inputStream, newFile.getContentType());

                // 更新 video_url 字段
                video.setVideo_url(newVideoUrl);
            }

            // 调用 Mapper 更新数据库
            return videosMapper.updateVideos(video) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}

